import {
  Component,
  ChangeDetectionStrategy,
  OnInit,
  OnDestroy,
  NgZone,
  ChangeDetectorRef,
  ElementRef,
  Input,
} from '@angular/core';
import { Subscription } from 'rxjs';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { ProductViewComponent } from '../../product-view/product-view.component';
import { Random } from 'mockjs';

/**
 * 产品库存
 */
@Component({
  selector: 'product-stock',
  templateUrl: './product-stock.component.html',
  styleUrls: ['./product-stock.component.less'],
  host: {
    '[class.card]': 'true',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductStockComponent implements OnInit, OnDestroy {
  private ref$: Subscription;
  private chart: any;
  loading = true;
  data = [];
  time: Date;
  showType = 'chart';
  sum = 0;
  show = true;
  @Input()
  sap = null;

  constructor(
    private p: ProductViewComponent,
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnInit(): void {
    this.ref$ = this.p.$refresh.subscribe(vo => {
      this.ngZone.runOutsideAngular(() => {
        this.attachData(this.sap);
      });
    });
  }

  ngOnDestroy(): void {
    this.ref$.unsubscribe();
  }

  render(er: ElementRef) {
    this.ngZone.runOutsideAngular(() => setTimeout(() => this.init(er.nativeElement), 50));
  }

  private init(container: HTMLElement) {
    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,
      height: 152,
      padding: 0,
    }));
    chart.tooltip(false);
    chart.legend(false);
    chart.coord('theta', {
      radius: 0.75,
    });

    chart
      .intervalStack()
      .position('count')
      .color('text', ['#99CCCC', '#FFCC99'])
      .opacity(1)
      .label('percent', {
        textStyle: {
          fill: '#666',
        },
        formatter: (val: any, item: any) => `${item.point.text}: ${item.point.count} 副`,
      });

    chart.render();
    if (this.sap) {
      this.attachData(this.sap);
    }
  }

  private attachData(sap) {
    const { chart, ngZone } = this;
    ngZone.run(() => {
      this.loading = true;
      this.cdr.detectChanges();
    });

    this.http.get(`/cf/prod/sys-prod/stock?sap=${sap}`).subscribe((res: any) => {
      ngZone.run(() => {
        if (res.data) {
          // tslint:disable-next-line: prefer-conditional-expression
          if (res.data.updateTime) {
            this.time = res.data.updateTime;
          } else {
            this.time = res.data.createTime;
          }
          this.data = [
            { text: '限制库存', count: res.data.limitStock, color: '#99CCCC' },
            { text: '定制库存', count: res.data.cmStock, color: '#FFCC99' },
          ];
          this.sum = this.data.reduce((p, c) => (p += c.count), 0);
          this.show = !(this.sum < 1);
        } else {
          this.show = false;
        }
        this.loading = false;
        this.cdr.detectChanges();
      });
      ngZone.runOutsideAngular(() => {
        const ds = new DataSet();
        const dv = ds.createView().source(this.data);
        dv.transform({
          type: 'percent',
          field: 'count',
          dimension: 'text',
          as: 'percent',
        });
        chart.changeData(dv);
      });
    });
  }
}
